<?php

App::uses('AdminController', 'Controller');

class AdminCeneController extends AdminController {
    
    public $uses = array( 'Price', 'PriceGroup' );
    
    public function index() {
        $groups = $this->PriceGroup->find('list');
        
        $this->set(compact('groups'));
    }
    
    public function group($groupId) {
        $this->layout = 'ajax';
        $prices = $this->Price->findAllByPriceGroupId($groupId);
        $units  = $this->Price->getUnits();
        
        $this->set(compact('prices', 'groupId', 'units'));
    }
    
    public function save($groupId) {
        $this->autoRender = false;
        if ($this->request->is('post')) {
            $data = $this->data;
            
            $this->Price->deleteAll(array(
                'Price.price_group_id' => $groupId
            ));
            if ($this->Price->saveAll($data)) {
                $this->setFlash('Sačuvano.', 'ok');
            } else {
                $message = 'Greška pri čuvanju podataka.';
                if (! empty($this->Price->validationErrors)) {
                    $message = 'Uneti podaci nisu validni.';
                }
                $this->errorHeader($message);
            }
        }
    }
    
    public function save_group() {
        $this->autoRender = false;
        if ($this->request->is('post')) {
            $data = $this->data;
            $this->PriceGroup->create($data);
            
            if (! $this->PriceGroup->validates()) {
                $this->errorHeader('Uneti podaci nisu validni.');
            }else if(! $this->PriceGroup->save($data)) {
                $this->errorHeader('Greška pri čuvanju podataka.');
            } else {
                $this->setFlash('Sačuvano.', 'ok');
            }
            
        }
    }

    public function delete_group($id) {
        $this->autoRender = false;
        if ($this->PriceGroup->delete($id)) {
            echo 'Grupa je obrisana.';
        } else {
            $this->errorHeader('Brisanje nije uspelo');
        }
    }
    
}
